<template>
  <div class="home-page">
    <div class="page-wrap">
      <div class="left-box">
        <div class="header-title-box"></div>
        <div class="left-header header">
          <div
            class="left-header-title"
            v-for="item in manList"
            :key="item.id"
            :style="{ height: (item.disHeight < disHeight ? disHeight : item.disHeight + 32) + 'px' }"
          >
            <div class="left-header-title-box">
              <div class="left-txt">
                <div class="left-img"></div>
                <div class="left-name">
                  {{ item.name }}
                </div>
              </div>
              <div class="right-time">
                <span>8h</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="right-box">
        <div class="right-header header">
          <div
            v-for="(item, index) in yearMonthData"
            :key="index"
            :style="{ width: item.width }"
            class="Gantt-table_header"
          >
            {{ item.yearMonthStr }}
          </div>
        </div>

        <div ref="tableDay" class="tableDay">
          <template v-for="(item, index) in dayView" :key="index">
            <div
              :ref="item.isToday ? 'todayRef' : 'null'"
              class="line-box"
              :class="[item.isToday ? 'today' : '', item.bool ? 'Gantt-table_weekend' : '']"
              :style="{ width: item.width }"
            >
              {{ item.dayWeekText }} {{ item.name }} {{ getMonthSuffix(item) }}
            </div>
          </template>
        </div>

        <div id="taskBarAryy">
          <div v-for="(item, index) in manList" :key="index" class="tableList" :style="tableListStyles">
            <!-- 背景盒子 -->
            <div
              class="bg-box-line"
              @mousedown="down"
              @mousemove="move"
              @mouseup="up(item, $event)"
              :style="{ height: (item.disHeight < disHeight ? disHeight : item.disHeight + 32) + 'px' }"
            >
              <div ref="movable.dom" class="move"></div>
              <template v-for="(ele, inx) in dayView" :key="inx">
                <div
                  class="line-item"
                  :class="[ele.bool ? 'bg-box-line_weekend' : '']"
                  :style="{ width: ele.width }"
                  @click="handleclick(item, ele)"
                  :ref="(dom) => push(dom, inx, item, ele)"
                >
                  <span :style="{ fontSize: '8px', userSelect: 'none' }"
                    >{{ ele.allYearMonthDayStr }} {{ item.disHeight }}</span
                  >
                </div>
              </template>
            </div>
            <!-- 任务条 -->
            <div class="jobs" v-if="false">
              <div
                class="job"
                v-for="(ele, i) in item.taskList"
                :style="{
                  left: ele.left + 'px',
                  width: ele.width + 'px',
                  height: ele.height + 'px',
                  position: ele.overlapInfo?.hasOverlap ? 'relative' : 'absolute',
                  background: ele.color,
                }"
                :key="ele.id"
                @click="handleEdit(ele, item)"
              >
                <span style="font-size: 10px; color: #fff; user-select: none"
                  >{{ ele.startDate }} - {{ ele.dateClosed }}</span
                >
              </div>
            </div>
            <!-- 任务条2 -->
            <div class="new-jobs">
              <div class="jobs-level" v-for="(newJob, ind) in item.newtaskList" :key="ind">
                <div
                  class="new-job"
                  v-for="(newItem, ind2) in newJob.children"
                  :key="ind2"
                  :style="{
                    top: newJob.maxHeight * ind + 'px',
                    left: newItem.left + 'px',
                    width: newItem.width + 'px',
                    height: newItem.height + 'px',
                    background: newItem.color,
                  }"
                  @click="handleEdit(newItem, item)"
                >
                  <span style="font-size: 10px; color: #fff; user-select: none"
                    >{{ newItem.startDate }} - {{ newItem.dateClosed }} {{ newJob.level }}</span
                  >
                </div>
              </div>
            </div>
            <!-- <div
              class="tableBar"
              :style="{
                width: item.offsetwidth,
                left: item.leftwidth,
                background: '#' + ((Math.random() * 0x1000000) << 0).toString(16).slice(-6),
              }"
            ></div> -->
            <div
              class="tableNameintro"
              :style="{
                left: item.tableNameintroWidth,
              }"
            >
              {{ item.taskName }}
            </div>
          </div>
        </div>
        <div class="Gantt-table_right_rew"></div>
        <div class="content"></div>
      </div>
    </div>
  </div>
  <t-dialog
    :header="dialogTitle"
    showOverlay
    draggable
    :closeBtn="false"
    v-model:visible="visible"
    :on-confirm="onConfirmAnother"
    :on-close="close"
  >
    <t-form :data="formData">
      <t-form-item label="负责人" name="name">
        <t-input v-model="formData.name" disabled placeholder="请输入负责人" />
      </t-form-item>
      <t-form-item label="小时" name="hour">
        <t-input v-model="formData.hour" disabled placeholder="请输入时间" />
      </t-form-item>
      <t-form-item label="花费小时/天" name="hour">
        <t-input v-model="formData.todoHour" @change="changeHour" placeholder="请输入花费时间" />
      </t-form-item>
      <t-form-item label="总花费" name="hour">
        <t-input v-model="formData.totalHour" disabled placeholder="请输入总花费" />
      </t-form-item>
      <t-form-item label="区间" name="date">
        <t-date-range-picker v-model="formData.date" @change="changeHour" :presets="presets" />
      </t-form-item>
      <t-form-item label="项目" name="project">
        <t-select v-model="formData.project" class="demo-select-base" clearable filterable>
          <t-option v-for="(item, index) in options" :key="index" :value="item.value" :label="item.label">
            {{ item.label }}
          </t-option>
        </t-select>
      </t-form-item>
      <t-form-item label="备注" name="remark">
        <t-textarea v-model="formData.remark" placeholder="请输入备注" />
      </t-form-item>
      <t-form-item label="选择颜色" name="color">
        <t-color-picker v-model="formData.color" :show-primary-color-preview="false" />
      </t-form-item>
    </t-form>
    <template #footer>
      <t-button theme="primary" @click="onConfirmAnother">确认</t-button>
      <t-button @click="visible = false" variant="outline">取消</t-button>
      <t-button style="position: absolute; left: 0" v-if="dialogTitle == '编辑'" theme="warning" @click="handleDelete"
        >删除</t-button
      >
    </template>
  </t-dialog>
</template>

<script setup>
// 渲染年月日
//日期渲染 日视图， 先获取当前日期，年月日，然后是想渲染前后几年的年份，前后几月的月份，前后几天的日期
// 开始渲染第一排是年月，一年的月份是固定的，所以都是可以写死的
// 这里有要注意一下的是，就是年月的宽度，因为要根据当月有多少天去计算宽度，所以我要知道，这一年这一月是多少天然后乘以40 下面是相关代码
import { getYear, getMonth, getDays, endOfMonth, formatNow } from '@/utils/date.js';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import { computed, watch } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';

// 设置 dayjs 的语言环境为中文
dayjs.locale('zh-cn');

// dayjs 获取当前时间

const currentToday = formatNow();

const currentYear = getYear();

const yearRange = 1; // 前后1年
const startDate = currentYear - yearRange; //前1年
const endDate = currentYear + yearRange; //后1年

const today = getDays(); // 当前天数
const currentMonth = getMonth() + 1; // 当前月份

const disWidth = 92; // 宽度
const disHeight = ref(160); // 高度

const displayedYears = {}; //用于记录已显示的年份

// console.log('开始年份', startDate);
// console.log('结束年份', endDate);
// console.log('当前天数', today);
// console.log('当前月份', currentMonth);
// console.log('当前月份最后一天', endOfMonth('2023', '12'));
const yearMonthData = ref([]); // 用于存储年月的数组
const weekData = ref([]); // 用于存储周的数组
const dateRange = ref([]); // 用于存储日期的数组
const dayView = ref([]); // 用于存储日视图的数组

// 一天8个小时  一周6天
const manList = ref([
  {
    id: 1,
    name: '赵晨',
    list: [],
    taskList: [
      {
        id: '1',
        taskName: '南沙明珠湾',
        startDate: '2024-01-01',
        dateClosed: '2024-01-03',
        todoHour: 8,
        color: '#660099',
      },
      // { id: '2', taskName: '玉环低碳', startDate: '2024-01-04', dateClosed: '2024-01-06', todoHour: 2 },
      // { id: '3', taskName: 'UE联调', startDate: '2024-01-02', dateClosed: '2024-01-02', todoHour: 4 },
      // { id: '4', taskName: 'UE联调-1', startDate: '2024-01-03', dateClosed: '2024-01-03', todoHour: 4 },
      // { id: '5', taskName: 'UE联调-2', startDate: '2024-01-03', dateClosed: '2024-01-05', todoHour: 4 },
    ],
  },
  {
    id: 2,
    name: '程浩',
    list: [],
    taskList: [],
  },
  {
    id: 3,
    name: '吕衍赐',
    list: [],
    taskList: [
      {
        id: '1',
        taskName: '南沙明珠湾',
        startDate: '2024-01-01',
        dateClosed: '2024-01-03',
        todoHour: 8,
        color: 'rgb(133, 219, 190)',
      },
      {
        id: '2',
        taskName: '玉环低碳',
        startDate: '2024-01-04',
        dateClosed: '2024-01-06',
        todoHour: 4,
        color: 'rgb(133, 219, 190)',
      },
      {
        id: '3',
        taskName: 'UE联调',
        startDate: '2024-01-02',
        dateClosed: '2024-01-02',
        todoHour: 4,
        color: 'rgb(133, 219, 190)',
      },
      {
        id: '4',
        taskName: 'UE联调-1',
        startDate: '2024-01-03',
        dateClosed: '2024-01-03',
        todoHour: 6,
        color: 'rgb(133, 219, 190)',
      },
      {
        id: '5',
        taskName: 'UE联调-2',
        startDate: '2024-01-02',
        dateClosed: '2024-01-03',
        todoHour: 2,
        color: 'rgb(133, 219, 190)',
      },
    ],
  },
]);

//渲染年月试图
const renderYearMonth = () => {
  // 外层循环，从开始年份 startDate 到结束年份 endDate
  for (let year = startDate; year <= endDate; year++) {
    // 中间的循环，遍历每一年的 12 个月份
    for (let month = 0; month < 12; month++) {
      // 提取出公共的日期部分
      const date = dayjs().year(year).month(month).toDate();

      // 使用 dayjs 计算每个月的最后一天
      const lastDay = dayjs(date).endOf('month').date();
      // 使用dayjs 计算每个月的周日的天数
      let nonSundayDays = 0; // 非周日的天数

      // 内层循环，从每个月的第一天到最后一天
      for (let day = 1; day <= lastDay; day++) {
        const currentDay = dayjs().year(year).month(month).date(day);
        // // 使用 dayjs 将每一天的日期对象添加到 dateRange 数组中
        // dateRange.value.push(dayjs().year(year).month(month).date(day));
        // 检查是否为周日
        if (currentDay.day() !== 0) {
          dateRange.value.push(currentDay);
          nonSundayDays++; // 如果不是周日，增加非周日的天数
        }
      }

      // 使用 dayjs 创建表示年份和月份的字符串，格式为 'YYYY-MM'
      const yearMonthStr = dayjs(date).format('YYYY-MM');

      // 使用模板字符串来创建宽度
      const width = `${nonSundayDays * disWidth}px`;

      // 将年份和月份的字符串以及宽度添加到 yearMonthData 数组中
      yearMonthData.value.push({
        yearMonthStr,
        width,
        nonSundayDays, // 添加非周日的天数
      });
    }
  }
  // console.log('yearMonthData', yearMonthData.value);
  if (dateRange.value.length > 0) renderDay();
};

//日试图的日渲染，标出周末以及当前日期深颜色
const renderDay = () => {
  // 遍历 dateRange 数组
  for (let i = 0; i < dateRange.value.length; i++) {
    // 获取当前日期
    const currentDate = dateRange.value[i];
    // 获取当前日期是星期几，0 表示星期日，1 表示星期一，以此类推
    const dayNumber = currentDate.day();

    // 判断当前日期是否为周末，如果是星期六或星期日，则为周末
    const isWeekend = dayNumber === 0 || dayNumber === 6;

    // 找到周末 去除周末
    const isWeekLast = dayNumber === 0;

    // 星期文案
    const weekTxtList = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];

    // 获取当前日期的日
    const dayText = currentDate.date(); // 使用dayjs获取当前日期的日 dayjs().date()
    const dayWeekText = weekTxtList[dayNumber]; // 使用dayjs获取当前日期的日 dayjs().date()

    const dayYear = currentDate.year(); // 获取当前日期的年份 dayjs().year()
    // 获取当前日期的月份，注意月份是从 0 开始的，0 表示一月，11 表示十二月
    const dayMonth = currentDate.month(); // dayjs().month()
    const currenTime = dayjs(currentToday).format('YYYY-MM-DD');
    // 根据年月日 转成 日期格式
    const dayDate = dayjs(`${dayYear}-${dayMonth + 1}-${dayText}`).format('YYYY-MM-DD');
    // 判断当前日期是否为今天，如果日、年份和月份都与今天相同，则为今天
    const isToday = currenTime === dayDate;
    // const isToday = dayText === today && dayYear === currentYear && dayMonth === currentMonth;
    // 获取当前渲染日期 2023-01 格式的字符串
    const yearMonthStr = currentDate.format('YYYY-MM');
    const allYearMonthDayStr = currentDate.format('YYYY-MM-DD');
    // 从 yearMonthData 数组中找到与当前日期相同的年份和月份的数据
    const yearMonthDataItem = yearMonthData.value.find((item) => item.yearMonthStr === yearMonthStr);
    // 获取 当前月份多少天
    const lastDay = dayjs(currentDate).endOf('month').date(); //

    // 从yearMonthDataItem拿到width 然后除以当前月份多少天 得到每天的宽度
    const width = `${yearMonthDataItem.width.replace('px', '') / yearMonthDataItem.nonSundayDays}px`;

    // 将日期的信息添加到 dayView 数组中，包括日（name）、是否为周末（bool）和是否为今天（isToday）
    dayView.value.push({
      name: currentDate.date(),
      dayYear,
      dayMonth,
      dayWeekText,
      allYearMonthDayStr,
      bool: isWeekend,
      isToday: isToday,
      yearMonthStr,
      yearMonthDataItem,
      lastDay,
      width,
      isWeekLast,
    });
  }
  // console.log('dayView', dayView.value);
};

renderYearMonth();

//辅助函数 处理传入的item 返回一个对象 包含宽度和距离和高度
const formarObj = (obj, i) => {
  const retrunObj = {
    left: '',
    width: '',
    height: '',
    top: '',
  };
  retrunObj.left = dayView.value.findIndex((item) => item.allYearMonthDayStr === obj.startDate) * disWidth;

  // 计算宽度
  const startDay = dayView.value.findIndex((item) => item.allYearMonthDayStr === obj.startDate);
  const endDay = dayView.value.findIndex((item) => item.allYearMonthDayStr === obj.dateClosed);
  retrunObj.width = (endDay - startDay + 1) * disWidth;

  // 根据 todoHour 计算高度
  const hourOne = 160 / 10; // 一小时的高度  16 空出来 16*2
  // 计算时间差
  const start = dayjs(obj.startDate);
  const end = dayjs(obj.dateClosed);
  const diff = end.diff(start, 'day') + 1;
  retrunObj.height = hourOne * obj.todoHour;
  // console.log(obj, i, '😭');
  // if (i === 0) {
  //   retrunObj.top = 0;
  // } else {
  // }
  // retrunObj.top = 16 + hourOne * (start.day() - 1);
  return retrunObj;
};

// 计算日期范围 传入最小日期和最大日期
const dataRangeFun = (a, b) => {
  const dateRange = [];
  const minDate = dayjs(a);
  const maxDate = dayjs(b);
  for (let i = 0; i <= maxDate.diff(minDate, 'day'); i++) {
    dateRange.push(dayjs(minDate).add(i, 'day').format('YYYY-MM-DD'));
  }
  return dateRange;
};

const processList = (list) => {
  let result = [];

  list.forEach((item, index) => {
    let newItem = { ...item };
    let maxLevel = -1;

    // 遍历前面的所有元素
    for (let i = 0; i < index; i++) {
      // 如果前面的元素的 dataRangeList 中包含当前元素的任何一个日期
      if (list[i].dataRangeList.some((date) => item.dataRangeList.includes(date))) {
        // 更新 maxLevel
        maxLevel = Math.max(maxLevel, parseInt(result[i].level.slice(1)));
      }
    }

    // 如果 maxLevel 仍然是 -1，说明没有任何一个日期在前面的元素中出现过，所以 level 为 "L0"
    // 否则，level 为 "L" + (maxLevel + 1)
    newItem.level = maxLevel === -1 ? 'L0' : 'L' + (maxLevel + 1);

    // 计算top的值，如果是第一个元素，那么top为0，否则为前一个元素的top + 前一个元素的高度
    newItem.top = index === 0 ? 0 : result[index - 1].top + result[index - 1].height;

    result.push(newItem);
  });

  return result;
};

const convertToMultiDimensionalArray = (list) => {
  return list.reduce((acc, item) => {
    const levelIndex = parseInt(item.level.slice(1));
    if (!acc[levelIndex]) {
      acc[levelIndex] = [];
    }
    acc[levelIndex].push(item);
    return acc;
  }, []);
};
const convertList = (list) => {
  let result = [];
  list.forEach((item, index) => {
    // 查找具有相同 level 的元素
    let levelItem = result.find((x) => x.level === item.level);

    if (levelItem) {
      // 如果找到了具有相同 level 的元素，那么将当前元素添加到 children 数组中，并更新 maxHeight
      levelItem.children.push(item);
      levelItem.maxHeight = Math.max(levelItem.maxHeight, item.height); // 更新 maxHeight
    } else {
      // 如果没有找到具有相同 level 的元素，那么创建一个新的元素，并将当前元素添加到 children 数组中
      result.push({
        level: item.level,
        // TODO 高度有问题
        maxHeight: item.height <= 128 ? item.height : 128,
        children: [item],
      });
    }
  });

  return result;
};

const renderData = (ele, str) => {
  manList.value.forEach((e) => {
    if (e.taskList.length) {
      // 初始化每个任务的属性
      for (let i = 0; i < e.taskList.length; i++) {
        e.taskList[i].dataRangeList = dataRangeFun(e.taskList[i].startDate, e.taskList[i].dateClosed);
        e.taskList[i].level = 'L0'; // 任务的层级
        const { left, width, height, top } = formarObj(e.taskList[i], i);
        e.taskList[i].left = left;
        e.taskList[i].width = width;
        e.taskList[i].height = height;
        e.taskList[i].top = top;
      }
      e.newtaskList = convertList(processList(e.taskList));
      // TODO 整体高度
      e.disHeight = 128;
    } else {
      e.newtaskList = [];
      e.disHeight = 0;
    }
  });
  console.log('manList', manList.value);
};

const activeClass = ref(0);
const getMonthSuffix = (item) => {
  if (activeClass.value === 1) {
    return ' 月';
  }
  return '';
};

onMounted(() => {
  tableRectangle(0);
  renderData();
});

const width = ref(null);
const newW = ref(null);
const tableDay = ref(null);
const todayRef = ref(null);
const dayRef = ref(null);
const jobsRef = ref(null);

const tableRectangle = (id) => {
  width.value = tableDay.value.offsetWidth;
  // console.log('width', width.value);
  const todayElement = todayRef.value;
  // console.log('todayElement', todayElement);
  // 将屏幕滚到视口位置
  if (todayElement) {
    todayElement[0].scrollIntoView({ behavior: 'auto', block: 'center', inline: 'center' });
  }
  newW.value = id == 0 ? 92 : 201; // 假设 id 是一个已知的变量
};

const tableListStyles = computed(() => {
  // return {
  //   width: width.value + 'px',
  //   background: `repeating-linear-gradient(to right, #DDDDDD, #DDDDDD 1px, transparent 1px, transparent ${newW.value}px)`,
  //   'border-bottom': '0px',
  //   'background-size': `${newW.value}px 100%`,
  // };
  return {
    width: width.value + 'px',
  };
});
// 后渲染日

const handleclick = (item, ele) => {
  console.log(item, ele);
  ele.active = true;
  item.active = true;
};

let selected = ref([]); //被选元素的索引
let items = ref([]); //存储所有dom

let push = (dom, index, item, ele) => {
  // console.log(index, item, ele);
  // item.items = [];
  item.list[index] = {
    selected: false,
    dom: dom,
    item,
    ele,
  };
  // items.value[index] = {
  //   selected: false,
  //   dom: dom,
  //   item,
  //   ele,
  // };
  // 循环遍历元素是否被选中
  // f.items[index] = {
  //   selected: false,
  //   dom: dom,
  //   item,
  //   ele,
  // }; //记录dom
};

/*
 * 初始的原点
 * */
let point = {
  /*
   * 鼠标起点坐标
   * */
  start: {
    x: 0,
    y: 0,
  },
  /*
   * 鼠标终点坐标
   * */
  end: {
    x: 0,
    y: 0,
  },
  /*
   * 是否正在move
   * */
  moving: false,
  /*
   * 获取范围内四个角的坐标
   * */
  getPosition() {
    let angle = []; //角

    angle.push(this.start); //起点
    angle.push(this.end); //终点

    angle.push({
      x: this.end.x,
      y: this.start.y,
    }); //对角

    angle.push({
      x: this.start.x,
      y: this.end.y,
    }); //对角

    return angle;
  },

  /*
   * 判断元素是否满足被选中的条件
   * */
  isSelected(rect) {
    let angle = point.getPosition(); //获取四个角的坐标

    /*
     * 获取指定图形的四个坐标
     * */
    let rectangle = [
      {
        x: rect.x,
        y: rect.y,
      },
      {
        x: rect.x + rect.width,
        y: rect.y + rect.height,
      },
      {
        x: rect.x + rect.width,
        y: rect.y,
      },
      {
        x: rect.x,
        y: rect.y + rect.height,
      },
    ];

    /*
     * 满足以下任意一个条件即可
     * */

    /*
     * 互相判断
     * */
    for (let pos of rectangle) {
      if (pos.x > angle[0].x && pos.x < angle[1].x && pos.y > angle[0].y && pos.y < angle[1].y) {
        return true;
      }
    }

    /*
     * 互相判断
     * */
    for (let pos of angle) {
      if (pos.x > rectangle[0].x && pos.x < rectangle[1].x && pos.y > rectangle[0].y && pos.y < rectangle[1].y) {
        return true;
      }
    }

    /*
     * 相交检测（横）
     * */
    if (
      angle[0].x < rectangle[0].x &&
      angle[1].x > rectangle[1].x &&
      angle[0].y > rectangle[0].y &&
      angle[1].y < rectangle[1].y
    ) {
      return true;
    }

    /*
     * 相交检测（竖）
     * */
    if (
      angle[0].x > rectangle[0].x &&
      angle[1].x < rectangle[1].x &&
      angle[0].y < rectangle[0].y &&
      angle[1].y > rectangle[1].y
    ) {
      return true;
    }

    return false;
  },
};

/*
 * 鼠标按下
 * 记录初始点击的位置
 * */
let down = (e) => {
  point.start.x = e.x;
  point.start.y = e.y;

  /*
   * 同步选择框的原点
   * */
  movable.left = e.x + 'px';
  movable.top = e.y + 'px';

  point.moving = true; //标记移动开始
};

/*
 * 鼠标移动
 * */
let move = (e) => {
  if (!point.moving) return;

  const { x, y } = e; //鼠标位置

  /*
   * 同步放大元素
   * */
  movable.height = Math.abs(point.start.y - y) + 'px';
  movable.width = Math.abs(point.start.x - x) + 'px';
};

/*
 * 鼠标抬起
 * */
let up = (eleDom, e) => {
  /*
   * 没有移动，直接终止
   * */
  if (!point.moving) return;

  movable.width = 0;
  movable.height = 0;
  point.end.x = e.x;
  point.end.y = e.y;
  point.moving = false;
  /*
   * 循环遍历元素是否被选中
   * */
  selected.value = []; //清空被选的索引

  // console.log(eleDom, e);
  eleDom.list.forEach((item, index) => {
    if (point.isSelected(item.dom.getBoundingClientRect())) {
      selected.value.push(item);
    }
  });
  // items.value.forEach((item, index) => {
  //   if (point.isSelected(item.dom.getBoundingClientRect())) {
  //     selected.value.push(item);
  //   }
  // });
  // console.log('终止选中g start', selected.value);
  // 打开弹窗
  openAddPop(eleDom, selected.value);
};

/*
 * 移动对象的属性
 * */
let movable = reactive({
  dom: null,
  top: 0,
  left: 0,
  width: 0,
  height: 0,
});
const visible = ref(false);
const formData = reactive({
  name: '赵晨',
  hour: '',
  todoHour: '',
  totalHour: '',
  date: [],
  color: '',
  project: '',
  remark: '',
});
const openAddPop = (dom, select) => {
  formData.id = '';
  // 随机数
  formData.uid = Math.floor(Math.random() * 1000000);
  visible.value = true;
  formData.name = dom.name;
  formData.project = [];
  formData.color = '#' + ((Math.random() * 0x1000000) << 0).toString(16).slice(-6);
  formData.remark = '';
  if (select.length == 1) {
    //只选了一个
    formData.date = [select[0].ele.allYearMonthDayStr, select[0].ele.allYearMonthDayStr];
    // formData.hour = 8;
  } else {
    formData.date = [select[0].ele.allYearMonthDayStr, select[select.length - 1].ele.allYearMonthDayStr];
    // formData.hour = 8 * select.length;
  }
  formData.hour = 8;
  formData.todoHour = 8;
  dialogTitle.value = '新增';
  console.log('打开了弹窗', dom, select);
};
const presets = ref({
  今天: [dayjs(), dayjs()],
});
const options = [
  { label: '玉环低碳', value: '玉环低碳' },
  { label: '南沙明珠湾', value: '南沙明珠湾' },
  { label: '永定河流域', value: '永定河流域' },
];
const onConfirmAnother = (context) => {
  console.log('formData.id', formData.id, formData.uid);
  //处理date ["2024-01-04", "2024-01-06"] 转成 startDate:2024-01-04 dateClosed:2024-01-06
  const startDate = dayjs(formData.date[0]).format('YYYY-MM-DD');
  const dateClosed = dayjs(formData.date[1]).format('YYYY-MM-DD');
  const obj = {
    id: formData.id ? formData.id : formData.uid,
    taskName: formData.project,
    startDate,
    dateClosed,
    todoHour: formData.todoHour,
    color: formData.color,
  };
  if (dialogTitle.value == '新增') {
    manList.value.forEach((e) => {
      if (e.name === formData.name) {
        e.taskList.push(obj);
      }
    });
  } else {
    console.log('编辑');
    if (formData.id) {
      manList.value.forEach((e) => {
        if (e.name === formData.name) {
          e.taskList.forEach((f) => {
            if (f.id === formData.id) {
              f.taskName = formData.project;
              f.startDate = startDate;
              f.dateClosed = dateClosed;
              f.todoHour = formData.todoHour;
              f.color = formData.color;
            }
          });
        }
      });
    }
  }
  console.log('点击了确认按钮', context, formData);
  MessagePlugin.success('提交成功');
  visible.value = false;
  renderData();
  // console.log(manList);
};

const dialogTitle = ref('新增');

const handleEdit = (dom, item) => {
  dialogTitle.value = '编辑';
  console.log('点击了编辑', dom, item);
  visible.value = true;
  formData.name = item.name;
  formData.project = dom.taskName;
  formData.todoHour = dom.todoHour;
  formData.date = [dom.startDate, dom.dateClosed];
  formData.color = dom.color;
  formData.id = dom.id;
};

const handleDelete = () => {
  console.log('点击了删除', formData.id, formData.name);
  manList.value.forEach((e) => {
    if (e.name === formData.name) {
      e.taskList.forEach((f, index) => {
        if (f.id === formData.id) {
          e.taskList.splice(index, 1);
        }
      });
    }
  });
  visible.value = false;
  renderData();
};

const close = () => {
  console.log('点击了关闭');
};
// formData.todoHour
watch(
  () => formData.todoHour,
  (val) => {
    const startDate = dayjs(formData.date[0]);
    const dateClosed = dayjs(formData.date[1]);
    const diff = dateClosed.diff(startDate, 'day') + 1;
    formData.totalHour = diff * formData.todoHour;
  },
);
const changeHour = () => {
  // console.log('changeHour');
  // 只能输入整数，超过8小时，自动变成8小时
  if (formData.todoHour > 8) {
    formData.todoHour = 8;
  }
  const startDate = dayjs(formData.date[0]);
  const dateClosed = dayjs(formData.date[1]);
  const diff = dateClosed.diff(startDate, 'day') + 1;
  formData.totalHour = diff * formData.todoHour;
};
</script>

<style lang="less" scoped>
.home-page {
  width: 100%;
  height: 100%;
  background-color: #fff;
  color: #000;

  .page-wrap {
    display: flex;
    width: 100%;
    // height: 800px;
    overflow: hidden;
    overflow-y: scroll;

    .left-box {
      width: 20%;
      // height:100%;
      // height: 900px;
      box-shadow:
        0 2px 4px rgba(0, 0, 0, 0.12),
        0 0 6px rgba(0, 0, 0, 0.04);
      box-sizing: border-box;

      // background-color: pink;
      .header-title-box {
        border-bottom: 1px solid #dddddd;
        height: 77px;
        box-sizing: border-box;
        // background: #660099;
      }
      .left-header-title {
        // min-height: v-bind(disHeight);
        min-height: v-bind("(disHeight) + 'px'");
        box-sizing: border-box;
        border-bottom: 1px solid #dddddd;
        padding: 10px;

        .left-header-title-box {
          display: flex;
          align-items: center;
          justify-content: space-between;

          .left-txt {
            display: flex;
            align-items: center;
            gap: 10px;
          }

          .right-time {
            background-color: rgb(248, 247, 249);
            color: rgb(52, 71, 101);
            border-radius: 6px;
            padding: 2px 4px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
          }

          .left-img {
            width: 20px;
            height: 20px;
            border-radius: 50%;
            background: #660099;
          }

          .left-name {
            font-size: 14px;
            letter-spacing: 1px;
          }
        }
      }
    }

    .right-box {
      width: 80%;
      box-sizing: border-box;
      // overflow: hidden;
      overflow-x: scroll;

      // .Gantt-table_right_rew {
      //   width: 1500px;
      //   overflow-x: scroll;
      //   text-align: left;
      // }
      .right-header {
        display: inline-flex;
        // width: 1500px;
        overflow-x: scroll;
        text-align: left;

        .Gantt-table_header {
          border: 1px solid #dddddd;
          border-right: 0px;
          text-align: center;
          border-bottom: 0px;
          line-height: 39px;
          height: 39px;

          &:nth-child(1) {
            border-left: 0px;
          }

          &:last-of-type {
            border-right: 1px solid #dddddd;
          }
        }
      }

      .tableDay {
        display: inline-flex;

        .line-box {
          line-height: 38px;
          width: 92px;
          height: 38px;
          border: 1px solid #dddddd;
          border-right: 0px;
          text-align: center;

          &:nth-child(1) {
            border-left: 0px;
          }

          &:last-of-type {
            border-right: 1px solid #dddddd;
          }
        }

        .Gantt-table_weekend {
          // background-color: #eeeeee;
          background: linear-gradient(
              -45deg,
              rgb(230, 230, 230) 12.5%,
              transparent 12.5%,
              transparent 50%,
              rgb(230, 230, 230) 50%,
              rgb(230, 230, 230) 62.5%,
              transparent 62.5%,
              transparent
            )
            0% 0% / 5px 5px;
        }
      }

      /* .tableList{width: 1500px;height: 40px;position: relative; background-color: white;} */
      .tableList {
        // width: 1200px;
        // height: 40px;
        // border: 1px solid #dddddd;
        // border-left: 0px;
        // border-top: 0px;
        // margin-left: -1px;
        display: flex;
        position: relative;
        align-items: center;
        .bg-box-line {
          display: inline-flex;
          padding-left: 1px;
          .line-item {
            width: 94px;
            // min-height: v-bind(disHeight);
            min-height: v-bind("(disHeight) + 'px'");
            border-bottom: 1px solid #dddddd;
            border-right: 1px solid #dddddd;
            text-align: center;
            // position: relative;
            // padding-bottom: 40px;
            // .bottom-box {
            //   position: absolute;
            //   left: 0;
            //   top: 20px;
            //   width: 100%;
            //   height: 40px;
            //   // background-color: rgb(98, 89, 99);
            // }

            &:nth-child(1) {
              border-left: 0px;
            }

            &:last-of-type {
              border-right: 1px solid #dddddd;
            }
          }
          .active {
            background-color: tomato;
          }
          .bg-box-line_weekend {
            // background-color: #eeeeee;
            background: linear-gradient(
                -45deg,
                rgb(230, 230, 230) 12.5%,
                transparent 12.5%,
                transparent 50%,
                rgb(230, 230, 230) 50%,
                rgb(230, 230, 230) 62.5%,
                transparent 62.5%,
                transparent
              )
              0% 0% / 5px 5px;
          }
        }
      }

      .tableList:hover {
        cursor: pointer;
        // background-color: #eeeeee;
      }
      .jobs {
        position: absolute;
        top: 0;
        left: 0px;
        .job {
          width: 200px;
          position: relative;
          border-radius: 4px;
          box-shadow:
            0 2px 4px rgba(0, 0, 0, 0.12),
            0 0 6px rgba(0, 0, 0, 0.04);
          top: 0;
          background-color: #660099;
          height: 65px;
        }
      }
      .new-jobs {
        position: absolute;
        top: 0;
        left: 0px;

        .jobs-level {
          // position: relative;
          position: absolute;
        }
        .new-job {
          position: absolute;
          width: 200px;
          border-radius: 4px;
          box-shadow:
            0 2px 4px rgba(0, 0, 0, 0.12),
            0 0 6px rgba(0, 0, 0, 0.04);
          top: 0;
          background-color: #660099;
          height: 65px;
          box-sizing: border-box;
          border-top: 3px solid #fff;
          border-right: 3px solid #fff;
        }
      }

      .tableBar {
        background: red;
        width: 200px;
        height: 15px;
        top: 15px;
        position: absolute;
        border-radius: 10px;
        left: 200px;
      }

      .tableNameintro {
        white-space: nowrap;
        position: absolute;
      }

      .tableBar:hover {
        border-radius: 0px;
      }

      .today {
        background-color: #660099;
        color: #ffffff;
      }
    }
  }
}
.move {
  position: fixed;
  top: v-bind('movable.top');
  left: v-bind('movable.left');
  width: v-bind('movable.width');
  height: v-bind('movable.height');
  background: rgba(234, 23, 135, 0.3);
}
.btn-position {
  position: absolute;
  bottom: 10px;
  left: 10px;
}
</style>
